package com.cds.drizzt.config;

import com.cds.drizzt.filter.JwtAuthenticationFilter;
import com.cds.drizzt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Autowired
    private UserService userService;

    @Bean
    public PasswordEncoder passwordEncoder()  {

        return new BCryptPasswordEncoder();
    }

    /**
     * 配置JWT认证过滤器
     * @return JWT认证过滤器对象
     */
    @Bean
    public JwtAuthenticationFilter authenticationJwtTokenFilter()  {

        return new JwtAuthenticationFilter();
    }

    /**
     * 配置DAO认证提供程序
     * @return 认证提供程序对象
     */
    @Bean
    public DaoAuthenticationProvider authenticationProvider()  {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    /**
     * 配置认证管理器
     * @param authConfig 认证配置对象
     * @return 认证管理器对象
     * @throws Exception 处理异常
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    // -------------------------- 1. 定义 CORS 规则（核心配置） --------------------------
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfig = new CorsConfiguration();

        // 1. 允许的源（生产环境建议指定具体域名，如 "https://your-frontend.com"，避免 "*"）
        corsConfig.setAllowedOriginPatterns(List.of("*")); // 开发环境临时使用 "*"，生产环境需替换

        // 2. 允许的请求方法（GET/POST/PUT/DELETE 等）
        corsConfig.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));

        // 3. 允许的请求头（如 Content-Type、Authorization）
        corsConfig.setAllowedHeaders(List.of("*"));

        // 4. 是否允许携带凭证（如 Cookie、Token，前后端分离场景通常需要开启）
        corsConfig.setAllowCredentials(true);

        // 5. 预检请求（OPTIONS）的缓存时间（秒），减少重复预检请求
        corsConfig.setMaxAge(3600L);

        // 将规则应用到所有路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);

        return source;
    }

    /**
     * 配置安全过滤器链
     * @param http HTTP安全对象
     * @return 安全过滤器链对象
     * @throws Exception 处理异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(
                    "/api/auth/**",
                    "/doc.html",
                    "/v3/api-docs/**",
                    "/swagger-ui.html",
                    "/swagger-ui/**",
                    "/webjars/**",
                    "/favicon.ico",
                    "/error"       // 错误处理路径，需要公开访问
                ).permitAll()
                .anyRequest().authenticated()
//                .anyRequest().permitAll()
            );

        http.authenticationProvider(authenticationProvider());
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
